<?php

/******************************************  
    * 更新数据库淘宝店铺推广链接
    *****************************************/
require_once ( 'config.inc.php' );

$DBInstance = new DB();

$totalProductCount = $DBInstance->GetValue("select count(*) from product_info_taobao");

$offset = $DBInstance->GetValue("select id from product_info where TIMESTAMPDIFF( DAY, modify_date, NOW()) >1 limit 0,1");

$perStep = 50;

//$logger = GetAuditLogger( "shopinfo_audit.log" );

while( $offset < $totalProductCount) {
	
    //每次更新不要太多，防止超过每分钟调用频率
    $ProductArr = $DBInstance->GetPlan("select p.id,pt.product_id,pt.taobao_id
        from product_info_taobao pt,product_info p where pt.product_id=p.id and p.id>0
        limit $offset,$perStep");
    
        $p = '';
    	foreach( $ProductArr as $product ) {
        
    		$p=$p.$product['taobao_id'].',';
    	}	
    	$p = substr($p,0,strlen($p)-1);    	
    	   	
//     	foreach( $ProductArr as $product ) {
//        
//    		$p1=$p1.$product['taobao_id'].'['.$product['id'].']'.',';
//    	}	    	
//    	echo $p1; echo '</br>';
    	
		$Taoapi = new Taoapi;	    
		$Taoapi->method = 'taobao.taobaoke.items.convert';
		$Taoapi->fields = 'num_iid,volume,click_url';
		$Taoapi->num_iids = $p; 
		$Taoapi->nick = TAOBAOKE_ID;
		$TaobaoData = $Taoapi->Send('get','xml')->getArrayData();

		
		if(edp_is_empty_string($Taoapi->getErrorInfo())&& isset($TaobaoData['taobaoke_items'])) {
			
			
			$updateArr=array();
			
			$m = 0;
			foreach( $TaobaoData['taobaoke_items']['taobaoke_item'] as $td){
	
				$updateArr[$m]['volume'] = $td['volume'];
				$updateArr[$m]['click_url'] = $td['click_url'];
				$updateArr[$m]['num_iid'] = $td['num_iid'];
				
			    foreach( $ProductArr as $product ) {
	        
	    			if($product['taobao_id'] == $td['num_iid']){
	    				$updateArr[$m]['product_id'] = $product['id'];
	    				break;
	    			}	
	    		}
	    						
				$m++;
			}
			
			//print_r($updateArr);
		
	    	foreach( $updateArr as $update ) {
	    	 	   	         
	            try {
	            	
	                $DBInstance->BeginTransaction();
	
	                $sql = "update product_info set volume='".$update['volume']."' where id =".$update['product_id'];
	
	                $DBInstance->Update( $sql );
	                
	                $sql = "update product_info_taobao set click_url='".$update['click_url']."' where product_id =".$update['product_id'];
	
	                $DBInstance->Update( $sql );	
	                                
	            }
	            catch( Exception $e) {
	            	
	            	print_r($TaobaoData);
	                $DBInstance->Rollback();
	                return false;
	            }
	
	            $DBInstance->Commit();
				
	    	}
	    	
	   		sleep(2);
	   		
		}		
    	
    $offset = $offset + $perStep;
    
}

$DBInstance->Disconnect();

echo "finished!";

?>
